<template>
  <!--考核关系维护-->
  <div class="table-container">
    <list :options="tree" @select="handleTreeSelect" @resize="resize" :custom-width="350" />
    <div class="table-content" style="width: calc(100% - 360px)">
      <a-spin :spinning="isRefresh">
        <BasicTable @register="registerTable">
          <!--插槽:table标题-->
          <template #tableTitle>
            <a-button type="primary" @click="handleRefresh" v-show="showBtn"> 批量刷新</a-button>
            <a-button type="primary" preIcon="ant-design:export-outlined" @click="handleExport">导出</a-button>
            <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="handleImport">导入</j-upload-button>
            <a-button preIcon="ant-design:edit-outlined" @click="batchEdit" v-if="!startEdit && showBtn"> 批量编辑</a-button>
            <a-button type="primary" preIcon="ant-design:save-outlined" @click="batchSave" v-if="startEdit && showBtn"> 保存</a-button>
            <a-button preIcon="ant-design:close-outlined" @click="editCancel" v-if="startEdit && showBtn"> 取消</a-button>
            <a-button type="primary" @click="handleSame(1)" v-show="showBtn">同步人资</a-button>
            <a-button type="primary" @click="handleSame(2)" v-show="showBtn">同步</a-button>
          </template>
          <!--操作栏-->
          <template #action="{ record }">
            <TableAction :actions="getTableAction(record)" />
          </template>
          <template #bodyCell="{ column, text, record }">
            <template v-if="column.editRow && column.editComponent === 'Switch'">
              <a-switch checkedChildren="是" unCheckedChildren="否" :checkedValue="'true'" :unCheckedValue="'false'" :disabled="!startEdit" size="small" v-model:checked="record[column['dataIndex']]" />
              <!-- <span v-else>
              {{ 'true' == text ? '是' : '否' }}
            </span> -->
            </template>
            <template v-if="column.editComponent === 'TreeSelect'">
              <a-tree-select v-if="startEdit" v-model:value="record[column['dataIndex'] + 'Name']" style="width: 100%" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择" :fieldNames="{
      children: 'children',
      label: 'name',
      value: 'name',
    }" allow-clear :tree-data="userData" :load-data="loadUserData" @select="(v, node) => {
        record[column['dataIndex']] = node.code;
      }
      " />
              <span v-else>
                {{ record[column['dataIndex'] + 'Name'] }}
              </span>
            </template>
            <template v-if="column.dataIndex === 'userPosType'">
              <a-select :options="workTypeData" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{
      label: 'text',
      value: 'value',
    }" />
            </template>
            <template v-if="column.dataIndex === 'personType'">
              <a-select :options="personList" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{
      label: 'name',
      value: 'code',
    }" />
            </template>
            <template v-if="column.dataIndex === 'perfLevelType'">
              <a-select :options="prefLevelList" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{
      label: 'text',
      value: 'value',
    }" />
            </template>
            <template v-if="column.dataIndex === 'prefSalaryType'">
              <a-select :options="prefSalaryList" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{
      label: 'text',
      value: 'value',
    }" />
            </template>
            <template v-if="column.dataIndex === 'prefSalaryWay'">
              <a-select :options="prefSalaryWayList" style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" allow-clear :fieldNames="{
      label: 'text',
      value: 'value',
    }" />
            </template>
            <template v-if="column.dataIndex === 'displayOrder'">
              <a-input-number style="width: 100%" v-model:value="record[column['dataIndex']]" v-if="startEdit" size="small" />
              <span v-else>
                {{ text }}
              </span>
            </template>
          </template>
        </BasicTable>
      </a-spin>
    </div>
  </div>
  <rel-modal @register="registerModal" @success="handleSuccess" />
</template>

<script setup>
//ts语法
import { BasicTable, TableAction } from '/@/components/Table';
import { useListPage } from '../../../components/hooks/useListPage';
import { useModal } from '/@/components/Modal';
import { columns, searchFormSchema } from './relationship.data';
import { batchUpdate, tableList, getColumn, refresh, deleteRelation, getDictByCode, getSame, getSamePeople } from './service';
import List from '../../../components/pageList/list.vue';
import { Modal } from 'ant-design-vue';
import RelModal from './relModal.vue';
import { getAsynKeyUser } from '../assessDepartment/service';
import { render } from '/@/utils/common/renderUtils';
import { initDictOptions } from '/@/utils/dict/index';
import { exportXls, importXls } from '../../../components/utils/index';
import { getPersonTypeListByType } from '/@/api/common/api';

const handleExport = () => {
  // name, url, params, isXlsx = false, methods = 'get'
  let exportParams = {
    name: '员工考核关系数据',
    url: '/base/baseRel/export',
    params: {
      orgCodes: selectedCodeList.join(','),
      ...getForm().getFieldsValue(),
    },
  };
  exportXls({ ...exportParams });
};

const handleImport = (file) => {
  let importParams = {
    url: '/base/baseRel/importExcel',
    params: {
      orgCodes: selectedCodeList.join(','),
      ...getForm().getFieldsValue(),
    },
    success: () => {
      reload();
    },
  };
  importXls({ file, ...importParams });
};

const isRefresh = ref(false);
let userData = ref([]);
//异步数据添加到人员树数据
const setTreeData = (list, id, data) => {
  list.forEach((l) => {
    if (l.id == id) {
      l.children = [...data];
    }
    if (l.children) {
      setTreeData(l.children, id, data);
    }
  });
};
//异步加载选人子节点
const loadUserData = (treeNode) => {
  return new Promise((resolve) => {
    const { id } = treeNode.dataRef;
    getAsynKeyUser({ parentId: id }).then((res) => {
      resolve(res);
      setTreeData(userData.value, id, res);
    });
  });
};
let init = ref(false); //表格是否渲染
const tree = {
  url: '/base/baseSuitunitOrg/findTree', //左侧树数据接口
  title: '绩效考核部门',
  fieldNames: {
    title: 'orgName', //替换树默认显示title字段
    key: 'orgCode',
  },
};
const dynamicId = new Date().getTime() + 'pageId';
const resize = (width) => {
  console.log(width);
  width = parseInt(width) + 10;
  let page = document.getElementById(dynamicId);
  page.style.width = `calc(100 % - ${width}+'px')`;
};
let selectedCodeList = []; //树选择的节点和其子节点
let spinning = ref(false);
let startEdit = ref(false);
let workTypeData = ref([]);
let personList = ref([]);
let prefLevelList = ref([]);
let prefSalaryList = ref([]);
let prefSalaryWayList = ref([]);
let showBtn = ref(false); //批量刷新等按钮默认false,左树点击后为true
const screenX = computed(() => {
  let width = document.body.clientWidth;
  let x = 1600;
  if (width < 2000) {
    x = 1600;
  }
  if (width < 1700) {
    x = 1350;
  }
  if (width < 1500) {
    x = 1200;
  }
  if (width < 1400) {
    x = 1100;
  }
  if (tree) {
    return x - 300;
  }
  return x;
});
//注册编辑弹窗
const [registerModal, { openModal: openModal = () => { } }] = useModal();

// 列表页面公共参数、方法
const { tableContext } = useListPage({
  designScope: 'user-list',
  spinning: () => (spinning.value = !spinning.value),
  tableProps: {
    api: tableList,
    columns: columns,
    immediate: false,
    size: 'small',
    formConfig: {
      // labelWidth: 200,
      schemas: searchFormSchema,
    },
    scroll: { x: screenX },
    actionColumn: {
      width: 120,
      fixed: 'right',
    },
    beforeFetch: (params) => {
      return Object.assign(params, { orgCodes: selectedCodeList.join(',') });
    },
  },
});
//注册table数据和方法
// eslint-disable-next-line @typescript-eslint/no-unused-vars,no-unused-vars
const [registerTable, { reload = () => { }, getDataSource = () => { }, setColumns = () => { }, getForm }] = tableContext;
// getDictByCode({ dictType: 'epm_work_type' }).then((res) => {
//   workTypeData.value = res.list;
// });
initDictOptions('epm_work_type').then((res) => {
  workTypeData.value = res || [];
});
getPersonTypeListByType().then((res) => {
  personList.value = res || [];
});
// initDictOptions('hub_person_type1').then((res1) => {
//   initDictOptions('hub_person_type2').then((res2) => {
//     personList.value = [...res1, ...res2] || [];
//   });
// });
initDictOptions('hub_perf_level_type').then((res) => {
  prefLevelList.value = res || [];
});
initDictOptions('hub_pref_salary_type').then((res) => {
  prefSalaryList.value = res || [];
});
initDictOptions('hub_pref_salary_way').then((res) => {
  prefSalaryWayList.value = res || [];
});
// //查询动态表头
// Promise.all([getColumn(), getAsynKeyUser()])
//   .then((res) => {
//     console.log(res);
//     userData.value = res[1];
//     res[0].forEach((r) => {
//       columns.push({
//         title: r.personRemark,
//         dataIndex: r.personField,
//         editRow: true,
//         editComponent: 'TreeSelect',
//         width: 300,
//         align: 'center',
//       });
//     });
//     //重设表头
//     nextTick(() => {
//       setColumns(columns);
//     });
//   })
//   .finally(() => {
//     init.value = true;
//   });

//递归查找树子节点
function getCodeList(node, codeList) {
  node.forEach((n) => {
    try {
      codeList.push(n.orgCode);
      if (n.children) {
        getCodeList(n.children, codeList);
      }
    } catch (e) {
      console.error(e);
    }
  });
}

//左侧树选择事件
const handleTreeSelect = (treeNode) => {
  selectedCodeList = [...treeNode.selectedKeys];
  showBtn.value = true;
  if (treeNode.data.children) {
    getCodeList(treeNode.data.children, selectedCodeList);
  }
  reload();
};

/**
 * 新增事件
 */
function handleRefresh() {
  Modal.confirm({
    title: '确认刷新',
    content: '确认要刷新考核关系吗？',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      isRefresh.value = true;
      spinning.value = true;
      refresh({ orgCodeList: selectedCodeList })
        .then(() => {
          reload();
        })
        .finally(() => {
          isRefresh.value = false;
          spinning.value = false;
        });
    },
  });
}
/**
 * 编辑事件
 */
async function handleEdit(record) {
  openModal(true, {
    record,
  });
}

/**
 * author:lhw
 * description: 删除事件
 * @params: @
 * date: 2023/2/15
 * lastModify: 2023/2/15
 */
async function handleDelete(record) {
  deleteRelation({ ids: record.id }).then((res) => {
    reload();
  });
}
/**
 * 成功回调
 */
function handleSuccess() {
  // createMessage.success('操作成功!');
  reload();
}

/**
 * 操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    },
    {
      label: '删除',
      popConfirm: {
        title: '确认删除数据吗？',
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}

/**
 * author:lhw
 * description: 批量编辑方法
 * @params: @
 * date: 2023/2/13
 * lastModify: 2023/2/13
 */
function batchEdit() {
  let records = getDataSource();
  records.forEach((r) => {
    try {
      r.onEdit(true);
    } catch (e) {
      console.error(e);
    }
  });
  startEdit.value = true;
}

/**
 * author:lhw
 * description: 批量编辑保存
 * @params: @
 * date: 2023/2/13
 * lastModify: 2023/2/13
 */
function batchSave() {
  let records = getDataSource();
  records.forEach((r) => {
    try {
      r.onEdit(false, true);
    } catch (e) {
      console.log(e);
    }
  });
  setTimeout(() => {
    let data = getDataSource();
    batchUpdate(data).then(() => {
      reload();
    }); //保存数据
    startEdit.value = false;
  }, 500);
}
//同步
function handleSame(type) {
  if (type == 1) {
    getSamePeople().then(() => { });
  } else {
    getSame().then(() => { });
  }
}

/**
 * author:lhw
 * description: 取消批量编辑
 * @params: @
 * date: 2023/2/13
 * lastModify: 2023/2/13
 */
async function editCancel() {
  let records = getDataSource();
  for (const r of records) {
    try {
      await r.onEdit(false, false);
    } catch (e) { }
  }
  startEdit.value = false;
  reload();
}
</script>
<style lang="less" scoped>
/deep/.ant-table-wrapper {
  padding: 16px !important;
}

.full-size {
  width: 100%;
  height: 100%;
}
</style>
